package com.onstar.cn.common.util;


public class SimpleCrypto {

	/**
	 * @param args
	 */

	// 加密
	public static String encrypt(String key, String clearText) {
		if(clearText == null || key == null){
			return null;
		}
		byte[] keyBytes = key.getBytes();
		byte[] textBytes = clearText.getBytes();

		int len = 0;
		if (keyBytes.length > textBytes.length) {
			len = textBytes.length;
		} else {
			len = keyBytes.length;
		}

		byte[] cs = new byte[len];
		for (int i = 0; i < len; ++i) {
			cs[i] = (byte) ((int) textBytes[i] ^ (int) keyBytes[i]);
		}

		if (textBytes.length > keyBytes.length) {
			System.arraycopy(cs, 0, textBytes, 0, len);
			return toHex(textBytes);
		} else {
			return toHex(cs);
		}
	}
	
	//解密
	public static String decrypt(String key, String encrypted){
		if(key == null || encrypted == null){
			return null;
		}
		byte []keyBytes = key.getBytes();
		byte []encryptedBytes = toByte(encrypted);
		
		int len = 0;
		if (keyBytes.length > encryptedBytes.length) {
			len = encryptedBytes.length;
		} else {
			len = keyBytes.length;
		}
		
		byte[] cs = new byte[len];
		for (int i = 0; i < len; ++i) {
			cs[i] = (byte) ((int) encryptedBytes[i] ^ (int) keyBytes[i]);
		}
		
		if (keyBytes.length < encryptedBytes.length) {
			System.arraycopy(cs, 0, encryptedBytes, 0, len);
			return new String(encryptedBytes);
		}else{
			return new String(cs);
		}
		
	}

	public static byte[] toByte(String hexString) {
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
					16).byteValue();
		return result;
	}

	public static String toHex(byte[] buf) {
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++) {
			appendHex(result, buf[i]);
		}
		return result.toString();
	}

	private final static String HEX = "0123456789ABCDEF";

	private static void appendHex(StringBuffer sb, byte b) {
		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
	}
}
